/*
 * Copyright 2012 The Netty Project
 *
 * The Netty Project licenses this file to you under the Apache License,
 * version 2.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations
 * under the License.
 */
package net.jueb.sniff4j.socksCroe;
import java.net.InetSocketAddress;

import net.jueb.sniff4j.extr.base.AbstractRuntime;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.socks.SocksInitRequestDecoder;
import io.netty.handler.codec.socks.SocksMessageEncoder;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;

/**
 * 管道/连接初始化类
 * 产生request请求对象
 * @author helin
 *
 */
public final class SocksServerInitializer extends ChannelInitializer<SocketChannel> {
	protected static final InternalLogger log = InternalLoggerFactory.getInstance(SocksServerInitializer.class);
	private final SocksMessageEncoder socksMessageEncoder = new SocksMessageEncoder();
    private final SocksServerHandler socksServerHandler = new SocksServerHandler();

    public SocksServerInitializer() {
    	
    }
    @Override
    public void initChannel(SocketChannel socketChannel) throws Exception {
    	//TODO 连接时IP认证
    	InetSocketAddress client=socketChannel.remoteAddress();
    	if(AbstractRuntime.getRuntime(socketChannel).getRefuseClients().contains(client))
    	{//如果此连接地址被拒绝，则断开连接
    		
    		log.debug("客户端"+client.getHostString()+"被拒绝连接!");
    		socketChannel.close();
    		return;
    	}
    	log.debug("代理客户端建立连接:"+client.getHostString()+":"+client.getPort());
        ChannelPipeline channelPipeline = socketChannel.pipeline();
        /**
         * 在管道建立连接后加入客户端首次请求解码器，该加密器只执行一次，然后就被移除了
         */
        channelPipeline.addLast(SocksInitRequestDecoder.getName(), new SocksInitRequestDecoder());
        channelPipeline.addLast(SocksMessageEncoder.getName(), socksMessageEncoder);
        /**
         * 该handler为业务处理，每次都会执行，
         */
        channelPipeline.addLast(SocksServerHandler.getName(), socksServerHandler);
    }
}
